package com.supers.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.supers.servlet.utils.StringUtils;

/**
 * 中控servlet：接收请求url，调用请求对应的后台处理类中的处理方法，处理用户请求
 * @author LC
 *
 */
public class ActionServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		super.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 1、获取uri：super-servlet/userAction.action
		 * 2、对uri进行解析，把userAction解析出来
		 * 3、获取到application
		 * 4、从application中把map提取出来
		 * 5、根据key:userAction把value:com.supers.servlet.action.userAction提取出来
		 * 6、利用java的反射机制调用value:com.supers.servlet.action.userAction类中的execute()方法执行业务逻辑
		 * 7、返回执行结果
		 */
		String uri = request.getRequestURI() ;
		String actionName = StringUtils.parse(uri) ;
		Map<String, String> map = (HashMap<String, String>) this.getServletContext().getAttribute("action") ;
		String actionClassName = map.get(actionName) ;
		try {
			Class actionClass = Class.forName(actionClassName) ;
			String httpRequest = "javax.servlet.http.HttpServletRequest" ;
			Class requestClass = httpRequest.getClass() ;
			String httpResponse = "javax.servlet.http.HttpServletResponse" ;
			Class responseClass = httpResponse.getClass() ;
			Method method = actionClass.getMethod("execute", requestClass, responseClass) ;
			//在调用execute()方法的时候把request、response参数传递进去
			String result = (String) method.invoke(actionClass.newInstance(),request,response) ;
			//返回执行结果
			request.getRequestDispatcher(result).forward(request, response) ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	

}
